package com.my.study.filter;

import com.alibaba.fastjson.JSON;
import com.my.study.config.InterfaceConfig;
import com.my.study.entity.vo.ResponseVO;
import com.my.study.enums.BusinessExceptionEnum;
import com.my.study.utils.JwtUtil;
import com.my.study.utils.SpringBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
//@WebFilter(urlPatterns = "/*", filterName = "InterfaceFilter")与启动类注解配合使用@ServletComponentScan||我采用FilterConfig注册(根据配置文件读取拦截信息)
public class InterfaceFilter implements Filter {

    @Autowired
    private InterfaceConfig interfaceConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("=============LoginFilter.init()=========");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (!interfaceConfig.isEnable()) {
            filterChain.doFilter(request, response);
        }
        String token = request.getHeader("Authorization");
        //token是否存在
        if (token != null) {
            //验证token是否正确
            boolean result = JwtUtil.checkToken(token);
            if (!result) {//无效
                outputStream(response);
            } else {//有效令牌则刷新
                String refreshToken = JwtUtil.refreshToken(token);
                response.setHeader("Authorization", refreshToken);
                filterChain.doFilter(request, response);
            }
        } else {
            outputStream(response);
        }
    }

    /**
     * @description: 向客户端返回响应信息（json格式）
     * @author wangdong
     * @date 2019/10/8 16:46
     */
    private void outputStream(ServletResponse servletResponse) throws IOException {
        ResponseVO response = ResponseVO.fail(Integer.valueOf(BusinessExceptionEnum.PERMISSION.code),
                BusinessExceptionEnum.PERMISSION.msg);
        servletResponse.setContentType("application/json; charset=utf-8");
        servletResponse.getWriter().write(JSON.toJSONString(response));
    }

    @Override
    public void destroy() {
        log.info("=============LoginFilter.destroy()=========");
    }
}
